﻿using UnityEngine;
using System.Collections;

public class Controls : MonoBehaviour {

	public float jumpForce = 150;
	public float movingSpeed = 5;


	private Animator animator;

	enum CharacterState
	{
		normal,
		jumping
	}

	public delegate void MonPetitTest();

	public static MonPetitTest monEventLol;

	CharacterState characterState;

	// Use this for initialization
	void Start () {
		characterState = CharacterState.normal;
		animator = this.GetComponent<Animator>();

		monEventLol += UneVoidLol;

	}

	void UneVoidLol()
	{
		Debug.Log ("prout");
	}


	
	// Update is called once per frame
	void Update () {

		//Jump
		if (Input.GetKey (KeyCode.Space) && characterState == CharacterState.normal) {
			rigidbody2D.AddForce (Vector2.up * jumpForce);
			characterState = CharacterState.jumping;
		} else if (!Input.GetKey (KeyCode.Space) && characterState == CharacterState.jumping && rigidbody2D.velocity.y > 0) {
			rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, 0);
		}

		// L/R deplacement
		if (Input.GetKey (KeyCode.LeftArrow)) {
			animator.SetInteger ("Direction", 1);
			rigidbody2D.velocity = new Vector2(-movingSpeed, rigidbody2D.velocity.y);
			if(transform.localScale.x > 0) {
				Vector3 scale = transform.localScale;
				scale.x *= -1;
				transform.localScale = scale;
			}
		} else if (Input.GetKey (KeyCode.RightArrow)) {
			animator.SetInteger ("Direction", 3);
			rigidbody2D.velocity = new Vector2(movingSpeed, rigidbody2D.velocity.y);
			if(transform.localScale.x < 0) {
				Vector3 scale = transform.localScale;
				scale.x *= -1;
				transform.localScale = scale;
			}
		} else {
			animator.SetInteger ("Direction", 0);
			rigidbody2D.velocity = new Vector2(0, rigidbody2D.velocity.y);
		}
	
	}

	void OnCollisionEnter2D(Collision2D collision)
	{
		Debug.Log ("enter collision");
		monEventLol.Invoke ();
		characterState = CharacterState.normal;
	}

	void OnCollisionExit2D(Collision2D collision)
	{
		Debug.Log ("exit collision");
		characterState = CharacterState.jumping;
	}
}
